// 通用请求方法封装
import qs from 'qs'
import md5Libs from './md5'
import {
	JsonSort
} from '@/utils/ksort'
const base64 = require('./base64.js').Base64
const host = process.env.VUE_APP_URL
// const host = 'http://fangyuan.121.soft1024.com/index.php/'
const app_name = 'wx99d17d5918a170f6'
const app_fangyuan = 'fangyuanfangyuanfangyuanfangyuan'
export default (url = '', data = {}, method = 'POST') => {
	let headers = {}
	let params = Object.assign({
			timestamp: (new Date().getTime() / 1000).toFixed(0),
			mock: '0',
			app_name,
		},
		data
	)
	// 加密签名sign
	let access_token = uni.getStorageSync('access_token')
	let member_id = uni.getStorageSync('member_id')
	// 获取 sign
	let str = ''
	for (let key in JsonSort(params)) {
		str += `${key}=${JsonSort(params)[key]}&`
	}
	let sort = `${str}app_fangyuan=${app_fangyuan}`
	params.sign = md5Libs.md5(sort)
	// authentication
	let authentication = ''
	if (access_token && member_id) {
		authentication = 'USERID ' + base64.encode(`${app_name}-${access_token}-${member_id}`)
	}

	if (method === 'POST') {
		headers = {
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
			authentication: authentication || '',
		}
	} else if (method === 'GET') {
		headers = {
			Accept: 'application/json',
			'Content-Type': 'application/json;charset=utf-8',
			authentication: authentication || '',
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${host}${url}`,
			method,
			data: params,
			dataType: 'json',
			header: headers,
			success(res) {
				if (res.statusCode === 200) {
					let {
						code,
						data,
						message
					} = res.data
					if (
						code != 200 &&
						code != 401 &&
						code != 402 &&
						message &&
						url !== '/order/v1/createOrder'
					) {
						uni.showToast({
							icon: 'none',
							title: message,
						})
					}
					if (code == 401 || code == 402) {
						uni.removeStorageSync('member_id')
						uni.removeStorageSync('access_token')
						uni.showToast({
							icon: 'none',
							title: `登录失效`,
							complete(res){
								uni.reLaunch({
									url:'/pages/user/login'
								})
							}
						})
					}
					resolve(res.data)
				} else {
					uni.showToast({
						icon: 'none',
						title: `${url}接口500了~~~`,
					})
				}
			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: `${url}接口500了~~~`,
				})
				reject(err)
			},
		})
	})
}
